package com.school.campus.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.date.DateTime;
import com.school.campus.domain.Post;
import com.school.campus.mapper.PostMapper;
import com.school.common.core.domain.entity.SysUser;
import com.school.common.utils.SecurityUtils;
import com.school.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.school.campus.mapper.CommentMapper;
import com.school.campus.domain.Comment;
import com.school.campus.service.ICommentService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 评论Service业务层处理
 *
 * @author wwj
 * @date 2025-11-03
 */
@Service
public class CommentServiceImpl implements ICommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询评论
     *
     * @param id 评论主键
     * @return 评论
     */
    @Override
    public Comment selectCommentById(Long id) {
        return commentMapper.selectCommentById(id);
    }

    /**
     * 查询评论列表
     *
     * @param comment 评论
     * @return 评论
     */
    @Override
    public List<Comment> selectCommentList(Comment comment) {
        return commentMapper.selectCommentList(comment);
    }

    /**
     * 新增评论
     *
     * @param comment 评论
     * @return 结果
     */
    @Override
    @Transactional
    public int insertComment(Comment comment) {
        Long userId = SecurityUtils.getUserId();

        SysUser sysUser = sysUserMapper.selectUserById(userId);
        Long postId = comment.getPostId();
        Post post = postMapper.selectPostById(postId);
        post.setCommentCount(post.getCommentCount() + 1);
        comment.setAvatar(sysUser.getAvatar());
        comment.setCommentator(SecurityUtils.getUsername());
        comment.setCommentTime(DateTime.now());
        int i = commentMapper.insertComment(comment);
        postMapper.updatePost(post);
        return i;
    }

    /**
     * 修改评论
     *
     * @param comment 评论
     * @return 结果
     */
    @Override
    public int updateComment(Comment comment) {
        return commentMapper.updateComment(comment);
    }

    /**
     * 批量删除评论
     *
     * @param ids 需要删除的评论主键
     * @return 结果
     */
    @Override
    public int deleteCommentByIds(Long[] ids) {
        return commentMapper.deleteCommentByIds(ids);
    }

    /**
     * 删除评论信息
     *
     * @param id 评论主键
     * @return 结果
     */
    @Override
    public int deleteCommentById(Long id) {
        return commentMapper.deleteCommentById(id);
    }
}
